package homework.james.xiao.server;

import homework.james.xiao.bean.Waiter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;

 
public class OrderServer implements Runnable{

		private ServerSocket orderSocket;
		private ExecutorService executorService;

		public OrderServer(ServerSocket orderSocket,ExecutorService executorService ){
			this.orderSocket = orderSocket;
			this.executorService = executorService;
		}
		@Override
		public void run() {
		 while(true){
	            Socket socket=null;
	            try {
	                //接收客户连接
	                socket=orderSocket.accept();
	                executorService.execute(new waiterThread(socket));                
	            }catch(SocketException e){
	            	if (e.getMessage().equals("Socket is closed"))
	            	break;
	            }
	            catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
		}
    	
    }
    
	class waiterThread implements Runnable{
		private Socket socket;
	    public waiterThread(Socket socket){
	        this.socket=socket;
	    }
	    
	    private BufferedReader getReader(Socket socket) throws IOException{
	        InputStream socketIn=socket.getInputStream();
	        return new BufferedReader(new InputStreamReader(socketIn,"UTF-8"));
	    }
	    private ObjectOutputStream getObjectOutputStream(Socket socket) throws IOException{
	        OutputStream socketOut=socket.getOutputStream();
	        return new ObjectOutputStream(socketOut);
	    }
		/**
		 * 处理用户请求
		 */
		public void run() {
			try {
	            System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort());
	            BufferedReader br=getReader(socket);
	            ObjectOutputStream oos = getObjectOutputStream(socket);
	            Waiter waiter = new Waiter(oos);
				String command="";
				while (true) {
					System.out.println("waiting for command from client");
					command = br.readLine(); // 读入从client传来的字符串
					System.out.println("command recevied: " + command);
					if(waiter.handleWithSerialize(command))//client要求断开
						break;
				}
	        } catch (IOException e) {
	            e.printStackTrace();
	        }finally{
	            try {
	                if(socket!=null)
	                    socket.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
			
		}

		
		
}
